import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/alert_business/video/comic_buy_alert.dart';
import 'package:tiktokadult/alert_business/video/vip_acg_dailog.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_model/media_content.dart';
import 'package:tiktokadult/hj_utils/api_service/common_service.dart';
import 'package:tiktokadult/tools_base/event_bus/event_bus_util.dart';
import 'package:tiktokadult/tools_base/event_bus/events.dart';

import '../../../hj_model/acg/comic_chapters_model.dart';
import '../../../hj_utils/api_service/acg_service.dart';
import '../../../hj_utils/global.dart';
import '../../../tools_base/global_store/store.dart';

//小说资源管理器
class ACGSourceManager extends ChangeNotifier {
  CartoonMediaInfo? mediaInfo; //acg模型
  List<ComicChapterInfo> allEpisodes = <ComicChapterInfo>[]; //子集
  final mediaContentCache = <int, MediaContent>{}; //缓存数据

  String id;
  int page = 1;
  int index = 0; //当前选中的index,下标从0开始

  ACGSourceManager(this.id);

  ACGSourceManager copy() {
    return ACGSourceManager(id)
      ..allEpisodes = allEpisodes
      ..page = page
      ..index = index;
  }

  updateLikeState(bool liked) {
    mediaInfo?.mediaStatus?.hasCollected = liked;
    notifyListeners();
  }

  //喜欢
  onLikeAction() async {
    final liked = mediaInfo?.mediaStatus?.hasLiked ?? false;
    int count = mediaInfo?.countLike ?? 0;
    final id = mediaInfo?.id ?? '';
    if (liked) {
      bool suc = await CommonService.cancelLike(id, mediaInfo?.mediaType ?? '');
      if (suc) {
        mediaInfo?.mediaStatus?.hasLiked = false;
        count--;
        mediaInfo?.countLike = count;
      }
    } else {
      bool suc = await CommonService.sendLike(id, mediaInfo?.mediaType ?? '');
      if (suc) {
        mediaInfo?.mediaStatus?.hasLiked = true;
        count++;
        mediaInfo?.countLike = count;
      }
    }
    notifyListeners();
  }

  //收藏操作
  onCollectAction() async {
    bool hasCollect = mediaInfo?.mediaStatus?.hasAddBookshelf ?? false;
    int count = mediaInfo?.countCollect ?? 0;
    if (hasCollect) {
      final res = await ACGService.mediaBookshelfDelete(mediaInfo?.id ?? '');
      if (res) {
        mediaInfo?.mediaStatus?.hasAddBookshelf = false;
        count--;
        mediaInfo?.countCollect = count;
        notifyListeners();
      }
    } else {
      final res = await ACGService.mediaBookshelfAdd(mediaInfo?.id ?? '');
      if (res) {
        mediaInfo?.mediaStatus?.hasAddBookshelf = true;
        count++;
        mediaInfo?.countCollect = count;
        notifyListeners();
      }
    }
  }

  //更新所有子集购买权限
  updatePermission({bool? buyAll, String? subId}) {
    if (buyAll == true) {
      mediaInfo?.mediaStatus?.hasPaid = true;
      allEpisodes.forEach((element) {
        element.hasBuy = true;
      });
    } else {
      allEpisodes.forEach((element) {
        if (element.id == subId) {
          element.hasBuy = true;
        }
      });
    }
    notifyListeners();
  }

  actionTitle() {
    int showCount = index + 1;
    String showText;
    if (showCount < 10) {
      showText = "00$showCount";
    } else if (showCount < 100) {
      showText = "0$showCount";
    } else {
      showText = showCount.toString();
    }
    if (showCount == 1) {
      return "立即阅读";
    } else {
      return "续看$showText${mediaInfo?.unit}";
    }
  }

  //切换子集 下标从0开始
  changeEpisodesIndex(int current, {bool jump = true}) {
    print('changeEpisodesIndex === $current');
    index = current;
    notifyListeners();
    if (jump) {
      eventBus.emit(ACGMenuChanged(index: index));
    }
  }

  //获取所有子集
  fetchAllEpisodes({bool isRefresh = false}) async {
    if (isRefresh) {
      page = 1;
      allEpisodes.clear();
    }
    final reslut = await ACGService.mediaContentChapterList(id, page, 20);
    if (reslut != null) {
      allEpisodes.addAll(reslut.list ?? []);
      notifyListeners();
      if (reslut.hasNext ?? false) {
        page += 1;
        fetchAllEpisodes(isRefresh: false);
      }
    }
  }

  //检测章节list权限 0:会员 1:金币购买 2:免费, 下标从0开始
  Future<ComicChapterInfo?> getEpisodeHasPermisson(int index_) async {
    if (allEpisodes.isEmpty) return null;
    final epm = allEpisodes[index_];

    final permission = mediaInfo?.permission ?? 0; // 查看父级权限
    Completer resultCom = Completer();
    bool hasPermission = false;
    //是否整本解锁
    bool unLock = mediaInfo?.mediaStatus?.hasPaid ?? false;
    bool isPremiumVIP = globalStore.isVIPTwoLevel(); //是否是高级会员
    print('getEpisodeHasPermisson unLock = $unLock, permission = $permission');
    if (unLock || isPremiumVIP) {
      hasPermission = true;
      resultCom.complete();
    } else {
      //0:会员 1:金币购买 2:免费,
      switch (permission) {
        case 2:
          hasPermission = true;
          resultCom.complete();
          break;
        case 0:
          hasPermission = globalStore.isVIP();
          if (!hasPermission) {
            await Get.dialog(VipACGDialog(), useSafeArea: false);
          }
          resultCom.complete();
          break;
        case 1:
          hasPermission = mediaInfo?.mediaStatus?.hasPaid ?? false;
          if (!hasPermission) {
            final result = await ComicBuyAlert.show(mediaInfo: mediaInfo);
            // 1 购买单集 2 购买全集，
            if (result == 1 || result == 2) {
              // 刷新所有章节
              hasPermission = true;
              if (result == 2) {
                updatePermission(buyAll: true); //
              }
              epm.hasBuy = true;
            }
            resultCom.complete();
          } else {
            resultCom.complete();
          }
          break;
        default:
      }
    }
    if (resultCom.isCompleted) {
      if (hasPermission) {
        changeEpisodesIndex(index_);
      }
    }
    return hasPermission ? epm : null;
  }

  // 获取漫画的子集
  Future<MediaContent?> getComicsMediaContent({int index = 0}) async {
    final mediaContent = mediaContentCache[index];
    if (mediaContent != null) return mediaContent;
    final mediaInfo = await getEpisodeHasPermisson(index);
    if (mediaInfo == null) return null;
    final result = await ACGService.getMediaDetailInfo(id: mediaInfo.id ?? '');
    if (result != null) {
      mediaContentCache[index] = result;
      return result;
    }
    return null;
  }

  //检测子集详情权限 0:会员 1:金币购买 2:免费
  checkPermission(MediaContent? model, {Function()? action}) async {
    //1.判断全集解锁权限
    if (mediaInfo?.mediaStatus?.hasPaid == true) {
      action?.call();
    } else if (model?.listenPermission == 2) {
      action?.call();
    } else if (model?.listenPermission == 0 && !globalStore.isVIP()) {
      await Get.dialog(const VipACGDialog());
      if (globalStore.isVIP()) {
        action?.call();
      }
    } else if (model?.listenPermission == 1 && (model?.hasBuy != true && mediaInfo?.mediaStatus?.hasPaid != true)) {
      var ret = await ComicBuyAlert.show(
        mediaInfo: mediaInfo?.updateStatus == 1 ? null : mediaInfo,
        curModel: ComicChapterInfo()
          ..mediaContent = model
          ..price = model?.price
          ..id = model?.id
          ..hasBuy = model?.hasBuy
          ..mediaId = model?.mediaId,
      );
      if (ret == 2 || ret == 1) {
        if (ret == 2) {
          updatePermission(buyAll: true);
        } else {
          updatePermission(subId: model?.id);
        }
        action?.call();
      }
    } else {
      action?.call();
    }
  }

  //上一集
  Future<ComicChapterInfo?> backToForward() async {
    debugPrint('当前播放的index $index 总共多少${allEpisodes.length}');
    if (index == 0) {
      showToast('当前是第一章～～～');
      return null;
    }
    final res = await getEpisodeHasPermisson(index - 1);
    return res;
  }

  //下一集
  Future<ComicChapterInfo?> jumpToNext() async {
    debugPrint('当前播放的index $index 总共多少${allEpisodes.length}');
    if (index == allEpisodes.length - 1) {
      showToast('当前是最后一章了～～～');
      return null;
    }
    final res = await getEpisodeHasPermisson(index + 1);
    return res;
  }

  @override
  void dispose() {
    super.dispose();
    print('dispose ===== NovelSourceManager');
  }
}

enum AudioPlayMod {
  loop,
  loopList,
}

class AudioPlayerValue {
  Duration? position;
  Duration? duration;
  bool? isPlaying;
  bool isLooping;
  double volume;
  bool isCompleted;
  bool isInitialized;
  int? onPlayIndex;

  AudioPlayerValue({
    this.position,
    this.duration,
    this.isPlaying,
    this.volume = 1,
    this.isLooping = true,
    this.isCompleted = false,
    this.isInitialized = false,
    this.onPlayIndex,
  });

  static AudioPlayerValue copyWith(AudioPlayerValue value) {
    return AudioPlayerValue(
      duration: value.duration,
      position: value.position,
      isPlaying: value.isPlaying,
      isCompleted: value.isCompleted,
      volume: value.volume,
      isLooping: value.isLooping,
      isInitialized: value.isInitialized,
      onPlayIndex: value.onPlayIndex,
    );
  }
}

//小说播放器管理
class AudioPlayerManager {
  AudioPlayerManager() {
    audioValue = ValueNotifier(value);
  }

  AudioPlayer? _audioPlayer;

  List<ComicChapterInfo> sourceList = []; // 播放源
  AudioPlayMod playMod = AudioPlayMod.loopList;
  String? title;

  Duration? totaDuration; // 总长度

  ACGSourceManager? sourceManger;

  StreamSubscription? _audioPositionSub;
  StreamSubscription? _audioDurationSub;
  StreamSubscription? _audioStateSub;
  StreamSubscription? _audioCompleSub;
  StreamSubscription? _audioErrorSub;
  StreamSubscription? _seekSub;

  final AudioPlayerValue value = AudioPlayerValue();

  late ValueNotifier<AudioPlayerValue> audioValue;

  double playSpeed = 1;

  initPlayer() {
    if (_audioPlayer == null) {
      _audioPlayer = AudioPlayer();
    }
    if (playMod == AudioPlayMod.loop) {
      _audioPlayer?.setReleaseMode(ReleaseMode.loop);
    } else {
      _audioPlayer?.setReleaseMode(ReleaseMode.stop);
    }

    // 总长度回掉
    _audioDurationSub = _audioPlayer?.onDurationChanged.listen((event) {
      totaDuration = event;
      audioValue.value = AudioPlayerValue.copyWith(value..duration = event);
    });

    // 播放进度回掉
    _audioPositionSub = _audioPlayer?.onPositionChanged.listen((event) {
      audioValue.value = AudioPlayerValue.copyWith(value
        ..position = event
        ..isPlaying = true
        ..onPlayIndex = (sourceManger?.index ?? 0));
    });
    // 播放状态回掉
    _audioStateSub = _audioPlayer?.onPlayerStateChanged.listen((event) {
      if (event == PlayerState.completed) {
        audioValue.value = AudioPlayerValue.copyWith(value
          ..isCompleted = true
          ..position = null);
      }
      if (event == PlayerState.playing) {
        audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = true);
      }
      if (event == PlayerState.paused) {
        audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = false);
      }
    });

    // 播放完成
    _audioCompleSub = _audioPlayer?.onPlayerComplete.listen((event) {
      if (playMod == AudioPlayMod.loopList && (value.isPlaying ?? false)) {
        audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = false);
        print(' _audioPlayer?.onPlayerCompletion.li${value.isPlaying}');
        playNext();
      } else {
        audioValue.value = AudioPlayerValue.copyWith(value
          ..isCompleted = true
          ..isPlaying = false);
      }
    });
    // 播放错误
    // _audioErrorSub = _audioPlayer?.onPlayerError.listen((event) {
    //   print('_audioPlayer ===== error $event');
    //   audioValue.value = AudioPlayerValue.copyWith(value
    //     ..isCompleted = true
    //     ..isPlaying = false
    //     ..duration = Duration.zero);
    // });

    //
    _seekSub = _audioPlayer?.onSeekComplete.listen((event) {
      audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = true);
    });

    audioValue.value = AudioPlayerValue.copyWith(value..isInitialized = _audioPlayer != null);
  }

  //播放第一集
  playFirst() {
    play(sourceManger!.allEpisodes[sourceManger!.index].getRealAudioUrl);
  }

  setPlaySpeed(double speed) {
    playSpeed = speed;
    _audioPlayer?.setPlaybackRate(speed);
  }

  // 开始播放
  play(String url) {
    if (_audioPlayer == null) {
      initPlayer();
    }
    if (url.isEmpty) {
      audioValue.value = AudioPlayerValue.copyWith(
        value
          ..isPlaying = false
          ..duration = null
          ..position = Duration.zero,
      );
      return;
    }

    audioValue.value = AudioPlayerValue.copyWith(
      value
        ..isPlaying = false
        ..duration = null
        ..position = Duration.zero,
    );
    // final sourceUrl = CacheServer().getLocalUrl(url) ??';
    _audioPlayer?.play(UrlSource(url));
  }

  // 播放下一集
  playNext() async {
    final epm = await sourceManger?.jumpToNext();
    if (epm != null) {
      play(epm.getRealAudioUrl);
    } else {
      pause();
    }
  }

  //播放上一集
  playForward() async {
    final epm = await sourceManger?.backToForward();
    if (epm != null) {
      play(epm.getRealAudioUrl);
    } else {
      pause();
    }
  }

  pause() async {
    await _audioPlayer?.pause();
    audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = false);
  }

  resume() async {
    await _audioPlayer?.resume();
    audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = true);
  }

  setPlayMod(AudioPlayMod mod) {
    if (mod == AudioPlayMod.loop) {
      _audioPlayer?.setReleaseMode(ReleaseMode.loop);
    } else {
      _audioPlayer?.setReleaseMode(ReleaseMode.stop);
    }
    playMod = mod;
    audioValue.value = AudioPlayerValue.copyWith(value..isLooping = mod == AudioPlayMod.loop);
  }

  playWithIndex(int index) async {
    if (index == sourceManger?.index) {
      if (!(value.isPlaying ?? false)) {
        resume();
        return;
      }
      return;
    }
    final epm = await sourceManger?.getEpisodeHasPermisson(index);
    if (epm != null) {
      play(epm.getRealAudioUrl);
    } else {
      pause();
    }
  }

  // 快进
  seek(int seconds) {
    _audioPlayer?.seek(Duration(seconds: seconds));
    if (value.isPlaying ?? false) {
      audioValue.value = AudioPlayerValue.copyWith(value..isPlaying = false);
    }
  }

  // 1前进 -1 后退
  seekTenMinsWithDirection(int dir) {
    int seconds = audioValue.value.position?.inSeconds ?? 0;
    final total = audioValue.value.duration?.inSeconds ?? 0;
    final diff = total - seconds;
    if (dir == -1) {
      if (seconds < 10)
        seconds = 0;
      else
        seconds -= 10;
    } else {
      if (diff < 10)
        seconds = total;
      else
        seconds += 10;
    }
    seek(seconds);
  }

  // 切换播放源
  resetDataSource(List<ComicChapterInfo> dataSource) {
    sourceList = dataSource;
  }

  dispose() {
    print('dispose ===== AudioPlayerManager');
    _audioPlayer?.pause();
    _audioPlayer?.release();
    _audioPlayer = null;
    _audioPositionSub?.cancel();
    _audioDurationSub?.cancel();
    _audioStateSub?.cancel();
    _audioCompleSub?.cancel();
    _seekSub?.cancel();
    _audioErrorSub?.cancel();
  }
}
